package com.yeziji.devops.config.aspect;

import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.datasource.DataSourceKey;
import com.yeziji.devops.annotation.DevopsService;
import com.yeziji.devops.common.DevopsKey;
import com.yeziji.devops.utils.ParseUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.Optional;

/**
 * devops 服务类切面拦截器
 *
 * @author hwy
 * @since 2024/08/15 18:10
 **/
@Slf4j
@Aspect
@Component
public class DevopsServiceAspect {
    @Around("@within(devopsService) || @annotation(devopsService)")
    public Object devopsServiceChooseDataSourceHandler(ProceedingJoinPoint pjp, DevopsService devopsService) throws Throwable {
        try {
            devopsService = ParseUtils.getAnnotation(pjp, DevopsService.class);
            // 这里会默认选择 master
            String dataSourceName = Optional.ofNullable(devopsService)
                    .map(DevopsService::name)
                    .filter(StrUtil::isNotBlank)
                    .orElse(DevopsKey.DataSource.MASTER);
            DataSourceKey.use(dataSourceName);
            return pjp.proceed();
        } finally {
            DataSourceKey.clear();
        }
    }
}
